package com.javatiaocao.myblog.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.javatiaocao.myblog.constant.CodeType;
import com.javatiaocao.myblog.mapper.FeedbackMapper;
import com.javatiaocao.myblog.mapper.UserMapper;
import com.javatiaocao.myblog.model.FeedBack;
import com.javatiaocao.myblog.model.User;
import com.javatiaocao.myblog.service.FeedbackService;
import com.javatiaocao.myblog.utils.DataMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FeedbackServiceImpl implements FeedbackService {
    @Autowired
    FeedbackMapper feedbackMapper;
    @Autowired
    UserMapper userMapper;
    /**
     * rows:data['data']['pageInfo']['pageSize'],//每页显示条数
     *                     pageNum:data['data']['pageInfo']['pageNum'],//当前所在页码
     *                     pages:data['data']['pageInfo']['pages'],//总页数
     *                     total:data['data']['pageInfo']['total'],//总记录数
     *
     *                     data['result']obj
     *                     obj['feedbackDate']
     *                     obj['person'] //根据id从user获得
     *                     obj['feedbackContent']
     *                     obj['contactInfo']
     * **/
    @Override
    public DataMap getAllFeedback(int rows, int pageNum) {
        PageHelper.startPage(pageNum,rows);
        List<FeedBack> feedBackList = feedbackMapper.getAllFeedback();
        if (feedBackList == null){
            return DataMap.fail(CodeType.SERVER_EXCEPTION);
        }
        JSONArray feedbackArray = new JSONArray();
        for (FeedBack feedBack : feedBackList) {
            User user = userMapper.selectUserById(feedBack.getPersonId());
            JSONObject feedbackObject = new JSONObject();
            feedbackObject.put("feedbackDate",feedBack.getFeedbackDate());
            feedbackObject.put("person",user.getUsername());
            feedbackObject.put("feedbackContent",feedBack.getFeedbackContent());
            feedbackObject.put("contactInfo",feedBack.getContactInfo());
            feedbackArray.add(feedbackObject);
        }
        PageInfo<FeedBack> feedBackPageInfo = new PageInfo<>(feedBackList);

        JSONObject pageInfo = new JSONObject();
        pageInfo.put("pageSize",feedBackPageInfo.getPageSize());
        pageInfo.put("pageNum",feedBackPageInfo.getPageNum());
        pageInfo.put("pages",feedBackPageInfo.getPages());
        pageInfo.put("total",feedBackPageInfo.getTotal());

        JSONObject returnObject = new JSONObject();
        returnObject.put("result",feedbackArray);
        returnObject.put("pageInfo",pageInfo);


        return DataMap.success().setData(returnObject);
    }


}
